package top.icecola.community.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import top.icecola.community.util.CommunityConstant;
import top.icecola.community.util.CommunityUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter implements CommunityConstant {
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers(
                "/user/setting",
                "/user/upload",
                "/discuss/add",
                "/comment/add/**",
                "/letter/**",
                "/notice/**",
                "/like",
                "/follow",
                "/unfollow"
        ).hasAnyAuthority(
                SECURITY_USER,
                SECURITY_ADMIN
        ).antMatchers(
                "/discuss/top",
                "/discuss/deletePost"
        )
         .hasAnyAuthority(
                 SECURITY_ADMIN
         )
         .anyRequest().permitAll()
        .and().csrf().disable();

        http.exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPoint() {
//           未登录时的处理
            @Override
            public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
                String xRequestedWith = httpServletRequest.getHeader("x-requested-with");
                if("XMLHttpRequest".equals(xRequestedWith)){
                  httpServletResponse.setContentType("application/plain;charset-utf-8");
                    PrintWriter writer = httpServletResponse.getWriter();
                    writer.write(CommunityUtil.getJSONString(403,"您还没有登录！"));
                }else{
                    httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login");
                }
            }
        }).accessDeniedHandler(new AccessDeniedHandler() {
//           权限不足
            @Override
            public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
                String xRequestedWith = httpServletRequest.getHeader("x-requested-with");
                if("XMLHttpRequest".equals(xRequestedWith)){
                    httpServletResponse.setContentType("application/plain;charset-utf-8");
                    PrintWriter writer = httpServletResponse.getWriter();
                    writer.write(CommunityUtil.getJSONString(403,"您的权限不足！"));
                }else{
                    httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/denied");
                }
            }
        });

//        覆盖Security底层默认的logout逻辑
        http.logout().logoutUrl("errorlogout");
    }
}
